package org.redemptionhost.web.panels;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.redemptionhost.HostQueries;
import org.redemptionhost.Repository;
import org.redemptionhost.model.Greeting;
import org.redemptionhost.model.Host;
import org.redemptionhost.model.HostAge;
import org.redemptionhost.web.pages.AdminPage;
import org.redemptionhost.web.pages.EditHostPage;

import com.google.appengine.api.datastore.Key;
import com.google.inject.Inject;

public class EditHostPanel extends Panel {
	private static final long serialVersionUID = 1L;
	
    @Inject
    public Repository<Host> hostRepository;

     @Inject
    private HostQueries hostQueries;
     
    private List<Host> fullHostList;
    
    public String selectedHost = " ";
	
	public EditHostPanel(String id) {
		super(id);
		
	       // This LoadableDetachableModel allows the following ListView<Greeting> to always load the latest persisted
        // Greeting entities on-demand, without having to store any model data in the session when this Guestbook page
        // gets serialized.
        LoadableDetachableModel<List<Host>> allHosts = new LoadableDetachableModel<List<Host>>()
        {
			private static final long serialVersionUID = 1L;

			@Override
            protected List<Host> load()
            {
                return hostQueries.all();
            }
        };

        DropDownChoice<String> hostNameField;
        {
        	ArrayList<String> nameList = new ArrayList<String>();
        	nameList.add(selectedHost);
        	fullHostList = hostQueries.all();
        	for (Host host : fullHostList) {
        		nameList.add(host.getFirstName() + " " + host.getLastName());
        	}
        	hostNameField = new DropDownChoice<String>("hostNameDDC", 
        			new PropertyModel<String>(this, "selectedHost"), nameList) {
						private static final long serialVersionUID = 1L;

				protected boolean wantOnSelectionChangedNotifications() {
        			return true;
        		}

        		@Override
        		protected void onSelectionChanged(final String newSelection) {
        			selectedHost = (String) newSelection;
        			for (Host current : fullHostList) {
        				String currName = current.getFirstName() + " " + current.getLastName();
        				
        				if (currName.equalsIgnoreCase(selectedHost)) {
        			        Form<Void> anotherEditForm = createDetail(current);
        			        this.getParent().addOrReplace(anotherEditForm);
        			        break;
        				}
        			}
        		}
            };
        }
    	add(hostNameField);
    	
        Form<Void> editHostForm = createDetail(new Host());
        addOrReplace(editHostForm);
	}
	
	private Form<Void> createDetail(final Host myHost) {
		Form<Void> returnValue = new Form<Void>("form") {
        	public String selectedAbbreviation = "  ";
        	public String selectedAge = " ";
        	private Host originalHost = myHost;
        	private Host updatedHost;
        	
            private RequiredTextField<String> firstNameField;
            {
            	firstNameField = new RequiredTextField<String>("firstName", new Model<String>(myHost.getFirstName()));
            	add(firstNameField);
            }

            private RequiredTextField<String> lastNameField;
            {
            	lastNameField = new RequiredTextField<String>("lastName", new Model<String>(myHost.getLastName()));
            	add(lastNameField);
            }

            private DropDownChoice<String> ageField;
            {
            	List<String> ageList = Arrays.asList(new String[] {
            			" ", "15", "16-17", "18 or older"
            	});
            	selectedAge = (myHost.getHostAge() == HostAge.FIFTEEN) ?
            			"15" : (myHost.getHostAge() == HostAge.SIXTEENSEVENTEEN) ?
            			"16-17" : "18 or older";
            	
            	ageField = new DropDownChoice<String>("ageDDC", 
            			new PropertyModel<String>(this, "selectedAge"), ageList);
            	add(ageField);
            }

            private RequiredTextField<String> streetAddressField;
            {
            	streetAddressField = new RequiredTextField<String>("streetAddress", new Model<String>(myHost.getStreetAddress()));
            	add(streetAddressField);
            }
           
            private RequiredTextField<String> cityField;
            {
            	cityField = new RequiredTextField<String>("city", new Model<String>(myHost.getCity()));
            	add(cityField);
            }

            private DropDownChoice<String> stateField;
            {
            	List abbreviations = Arrays.asList(new String[] {
            			"  ", "AB", "AK", "AL", "AR", "AZ", "BC", "CA", "CO", "CT", 
            			"DC", "DE", "FL", "GA", "HI", "IA", "ID", "IL", "IN", "KS",
            			"KY", "LA", "MA", "MB", "MD", "ME", "MI", "MN", "MO", "MS",
            			"MT", "NB", "NC", "ND", "NE", "NH", "NJ", "NL", "NM", "NS",		
            			"NT", "NU", "NV", "NY", "OH", "OK", "ON", "OR", "PA", "PE",		
            			"QC", "RI", "SC", "SD", "SK", "TN", "TX", "UT", "VA", "VT",
            			"WA", "WI", "WV", "WY", "YT" });
            	selectedAbbreviation = myHost.getState();
            	stateField = new DropDownChoice<String>("stateDDC", 
            			new PropertyModel(this, "selectedAbbreviation"), abbreviations);
            	add(stateField);
            }
            
           private RequiredTextField<String> zipField;
           {
        	   zipField = new RequiredTextField<String>("zip", new Model<String>(myHost.getZip()));
        	   add(zipField);
           }
            
            private RequiredTextField<String> phoneField;
            {
            	phoneField = new RequiredTextField<String>("phone", new Model<String>(myHost.getPhone()));
            	add(phoneField);
            }
            
            private RequiredTextField<String> emailField;
            {
            	emailField = new RequiredTextField<String>("email", new Model<String>(myHost.getEmail()));
            	add(emailField);
            }

            private RequiredTextField<String> redemptionCodeField;
            {
            	redemptionCodeField = new RequiredTextField<String>("redemptionCode", new Model<String>(myHost.getRedemptionCode()));
            	add(redemptionCodeField);
            }

            private CheckBox administratorField = new CheckBox("isAdministrator", new Model<Boolean>(myHost.getIsAdministrator()));
            {
            	add(administratorField);
            }
                     
            private CheckBox activeField = new CheckBox("isActive", new Model<Boolean>(myHost.getIsActive()));
            {
            	add(activeField);
            }
                     
            @Override
            protected void onSubmit()
            {
                String firstName = firstNameField.getModelObject();
                String lastName = lastNameField.getModelObject();
                String ageString = ageField.getModelObject();
                HostAge age = (ageString.equalsIgnoreCase("15")) ?
                		HostAge.FIFTEEN : (ageString.equals("16-17")) ?
                		HostAge.SIXTEENSEVENTEEN : HostAge.EIGHTEENPLUS;                
                String streetAddress = streetAddressField.getModelObject();
                String city = cityField.getModelObject();
                String state = stateField.getModelObject();
                String zip = zipField.getModelObject();
                String phone = phoneField.getModelObject();
                String email = emailField.getModelObject();
                String redemptionCode = redemptionCodeField.getModelObject();
                Boolean administrator = administratorField.getModelObject();
                Boolean active = activeField.getModelObject();

                Host updatedHost = new Host(
                		firstName,
                		lastName,
                		age,
                		streetAddress,
                		city,
                		state,
                		zip,
                		phone,
                		email,
                		redemptionCode,
                		administrator
                	);
                updatedHost.setIsActive(active);
                
                hostRepository.runInTransaction(new Junk(originalHost.getKey(), updatedHost));
                
                setResponsePage(EditHostPage.class);
            }
  
            class Junk implements Runnable
            {
            	Key key;
            	Host u;
            	public Junk(Key key, Host updated) {
            		this.key = key;
            		this.u = updated;
            	}
            	
				@Override
				public void run() {
					Host o = hostRepository.get(key);
					
					o.setFirstName(u.getFirstName());
					o.setLastName(u.getLastName());
					o.setHostAge(u.getHostAge());
					o.setStreetAddress(u.getStreetAddress());
					o.setCity(u.getCity());
					o.setState(u.getState());
					o.setZip(u.getZip());
					o.setPhone(u.getPhone());
					o.setEmail(u.getEmail());
					o.setRedemptionCode(u.getRedemptionCode());
					o.setIsAdministrator(u.getIsAdministrator());
					o.setIsActive(u.getIsActive());
				}
            }
        };
        return returnValue;

	}
}
